<?php

namespace addons\shopro\controller\goods;

use addons\shopro\controller\Common;
use addons\shopro\icbc\ICBCPayBizContentParameter;
use addons\shopro\library\notify\Notify;
use addons\shopro\service\goods\GoodsService;
use addons\shopro\service\pay\PayOper;
use addons\shopro\service\user\User as UserService;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Individuality;
use app\admin\model\shopro\Admin;
use app\admin\model\shopro\Bonus;
use app\admin\model\shopro\BonusLog;
use app\admin\model\shopro\commission\Level;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Config;
use app\admin\model\shopro\StorePerformance;
use app\admin\model\shopro\ThirdOauth;
use app\admin\model\shopro\trade\Order;
use app\admin\model\shopro\user\GoodsLog;
use app\admin\model\shopro\activity\Activity;
use app\admin\model\shopro\user\User;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\WalletLog;
use fast\Http;
use IcbcSignature;
use think\Db;
use WebUtils;

class Goods extends Common
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $params = $this->request->param();

        $keyword = $params['keyword'] ?? '';
        $ids = $params['ids'] ?? '';
        $category_id = $params['category_id'] ?? '';
        $is_category_deep = $params['is_category_deep'] ?? true;
        $sort = $params['sort'] ?? 'weigh';
        $order = $params['order'] ?? 'desc';

        $service = new GoodsService(function ($goods) {
            $goods->activities = $goods->activities;
            $goods->promos = $goods->promos;
            return $goods;
        });

        $service->up()->with(['max_sku_price' => function ($query) {      // 计算价格区间用(不知道为啥 with 必须再 show 后面)
            $query->where('status', 'up');
        }]);

        if ($keyword) {
            $service->search($keyword);
        }
        if ($ids) {
            $service->whereIds($ids);
        }
        if ($category_id) {
            $service->category($category_id, $is_category_deep);
        }

        if ($sort) {
            $service->order($sort, $order);
        }


        $goods = $service->paginate();

        $this->success('获取成功', $goods);
    }
    /**
     * 通过 ids 获取商品（不分页）
     *
     * @return void
     */
    public function ids() 
    {
        $params = $this->request->param();

        $ids = $params['ids'] ?? '';

        $service = new GoodsService(function ($goods) {
            $goods->activities = $goods->activities;
            $goods->promos = $goods->promos;
            return $goods;
        });

        $service->show()->with(['max_sku_price' => function ($query) {
            $query->where('status', 'up');
        }]);

        if ($ids) {
            $service->whereIds($ids);
        }
        $goods = $service->select();

        $this->success('获取成功', $goods);
    }
    public function reducePayment($user,$order, $order_type)
    {
        $order_data=[
            'order_id' => $order->id,
            'order_sn' => $order->order_sn,
            'order_type' => $order_type,
        ];
        $user_agnet=UserModel::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where(["id"=>$user["id"]])->find();//查找下单用户
        if(!empty($user_agnet) && isset($user_agnet["agent"]["level_info"]["level"]) && $user_agnet["agent"]["level_info"]["level"]>2){
            //扣除自己货款
            //WalletService::changePayment($user, 'payment_goods', -$order["pv_price"], 'payment_goods_order_pay',$order_data,'扣除货款',$user_agnet["id"]);
            //增加余额
            $commiss_rule=$user_agnet["agent"]["level_info"]["commission_rules"];
            $money=bcmul($order["pv_price"],($commiss_rule["commission_1"]/100),2);//上级余额成本
            //WalletService::changePayment($user, 'money', $order["pv_price"], 'payment_goods_order_pay_cost', $order_data,'自购增加余额',$user_agnet["id"]);
            WalletService::changePayment($user, 'money', $order["goods_amount"], 'payment_goods_order_pay_cost', $order_data,'自购增加余额',$user_agnet["id"]);
        }elseif(!empty($user_agnet["parent_user_id"])){
            //上级不为空
            $agent=$this->checkSellAgent($user_agnet["parent_user_id"]);
            /*$agent=UserModel::with(['agent' => function ($query) {
                return $query->with('level_info');
            }])
                ->where(["id"=>$user_agnet["parent_user_id"]])->find();//查找下单用户上级*/
            if(!empty($agent) && isset($agent["agent"])){
                //上级扣除货款
                WalletService::changePayment($agent["id"], 'payment_goods',-$order["pv_price"], 'payment_goods_order_pay', $order_data,'扣除货款',$user_agnet["parent_user_id"]);
                $rate=$agent["agent"]["level_info"]["commission_rules"]["commission_1"];//上级实际增加成本
                $parent_money=bcmul($order["pv_price"],($rate/100),2);//上级余额成本
                //增加商品成本余额
                WalletService::changePayment($agent["id"], 'money', $parent_money, 'payment_goods_order_pay_cost', $order_data,'出货成本',$user_agnet["id"]);
                $self_rate=$user_agnet["agent"]["level_info"]["commission_rules"]["commission_1"]>0?$user_agnet["agent"]["level_info"]["commission_rules"]["commission_1"]:100;
                $commiss=!empty($self_rate)?bcmul($order["pv_price"],($self_rate/100),2):$order["pv_price"];//购买者成本
                $commiss=bcsub($commiss,$parent_money,2);//购买者成本-上级成本
                //增加商品收益
                WalletService::changePayment($agent["id"], 'money', $commiss, 'payment_goods_order_pay_income', $order_data,'出货价差奖',$user_agnet["id"]);
                /*//扣除收益5%充值到货款
                $cut_payment=bcmul($commiss,0.05,2);//收益5%
                WalletService::changePayment($agent["id"], 'money', -$cut_payment, 'payment_goods_order_pay_income', $order_data,'扣除出货价差奖收益5%计入货款',$agent["parent_user_id"]);
                //扣除收益5%充值到货款
                $cut_payment_goods=bcdiv($cut_payment,($rate/100),2);//货款
                WalletService::changePayment($agent["id"], 'payment_goods', $cut_payment_goods, 'money_cut_payment_order_pay', $order_data,'扣除出货价差奖收益5%计入货款',$agent["parent_user_id"]);
                */
            }
        }
        return true;
    }
    /**
     * 奖金池
     * */
    public function bonus($user,$order)
    {
        $config = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        if(!empty($config) && $config["status"]==1){
            //开启奖金池
            $config["bonus_rate"]=$config["bonus_rate"]??3;
            $money=bcmul($order["pv_price"],($config["bonus_rate"]/100),2);//计入奖金池金额
            $momo=$user["nickname"]."【".$user["level"]."】下单，";
            $bonusModel= new Bonus();
            $bonus=$bonusModel::lock(true)->find();
            if(empty($bonus)){
                $bonusModel->save([
                    "money"=>$money,
                    "createtime"=>time(),
                ]);
            }else{
                $bonus->setInc("money",$money);
            }
            //生成奖金池记录
            $logModel= new BonusLog();
            $log=$logModel->where(["user_id"=>$user["id"],"order_id"=>$order["id"]])->find();
            if(empty($log)){
                $logModel->save([
                    "money"=>$money,
                    "order_id"=>$order["id"],
                    "order_pv"=>$order["pv_price"],
                    "order_details"=>json_encode($order),
                    "user_id"=>$user["id"],
                    "createtime"=>time(),
                    "momo"=>$momo,
                    "order_no"=>$order["order_sn"],
                    "ratio"=>$config["bonus_rate"],
                ]);
            }
        }
    }
    /**
     * 查找出货上级
     * */
    public function checkAellAgent($user_id,$level=0)
    {
        $data=[];
        $user=User::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where(["id"=>$user_id])->find();//查找下单用户
        if(!empty($user["parent_user_id"])){
            $parent_user=User::with(['agent' => function ($query) {
                return $query->with('level_info');
            }])
                ->where(["id"=>$user["parent_user_id"]])->find();//查找下单用户上级
            if(!empty($parent_user)){
                // 扣除上级货款
                $parent_level=$parent_user["agent"]["level_info"]["level"]??0;
                $user_level=$user["agent"]["level_info"]["level"]??0;
                if($level>0){
                    $user_level=$level;
                }
                if(!empty($parent_level) && $parent_level>$user_level){
                    //上级等级高于下单用户等级
                    $data=$parent_user;
                }else{
                    return $this->checkAellAgent($parent_user["id"],$user_level);
                }
            }
        }
        return $data;
    }
    /**
     * 查找出货上级---2023-12-28 修改
     * 按照推荐关系查找微店主及以上用户
     * */
    public function checkSellAgent($user_id)
    {
        $user=User::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where(["id"=>$user_id])->find();//查找下单用户上级
        $level=$user["agent"]["level_info"]["level"]??0;
        if($level<3){
            //查找上级
            if(!empty($user["parent_user_id"])){
                return $this->checkSellAgent($user["parent_user_id"]);
            }
            return [];
        }
        return $user;
    }

    /**
     * 统计优秀市场奖
     * */
    public function market($user,$order)
    {
        $config = ShoproConfig::getConfigs('shop.bonus.bonus_market', false);
        if(!empty($config) && $config["status"]==1){
            //开启优秀市场奖
            $user_agnet=User::with(['agent' => function ($query) {
                return $query->with('level_info');
            }])
                ->where(["id"=>$user["id"]])->find();//查找下单用户
            if(!empty($user_agnet))
            {
                if($user_agnet["is_store"]==1){
                    //下单用户就是门店
                    $user_id=$user_agnet["id"];
                }else{
                    $user_id=0;
                    if(!empty($user_agnet["agent"])){
                        //查找离下单用户最近的门店
                        $user_id=$this->getParent($user_agnet["id"]);
                    }
                }
                if(!empty($user_id)){
                    $money=bcmul($order["pv_price"],($config["divvy_rate"]/100),2);//计入奖励金额
                    //优秀市场奖记录
                    $logModel= new StorePerformance();
                    $log=$logModel->where(["user_id"=>$user_id,"order_id"=>$order["id"]])->find();
                    if(empty($log)){
                        $logModel->save([
                            "money"=>$money,
                            "order_id"=>$order["id"],
                            "order_pv"=>$order["pv_price"],
                            "order_details"=>json_encode($order),
                            "user_id"=>$user_id,
                            "createtime"=>time(),
                            "order_no"=>$order["order_sn"],
                            "ratio"=>$config["divvy_rate"],
                        ]);
                    }
                }

            }
        }
    }
    /**
     * 查找最近的门店
     * */
    public function getParent($members_id) {
        $members = UserModel::getById($members_id);
        if(!empty($members)){
            if(!empty($members["parent_user_id"])){
                $rows =UserModel::field("id,is_store")->where(["id"=>$members["parent_user_id"]])->find();
                if(!empty($rows)){
                    if($rows["is_store"]==1){
                        return $rows["id"];
                    }else{
                        return self::getParent($rows['id']);
                    }
                }else{
                    return 0;
                }
            }
        }
    }
    //新增 lina end
    public function detail()
    {
        /*$order=\app\admin\model\shopro\order\Order::find(40);
         $user=User::find($order["user_id"]);
         $res1=$this->reducePayment($user,$order, "order");
         dump($res1);die();*/
         /*$order=Order::find(535311);
         $user=User::find($order["user_id"]);
         $money=100.00;
         WalletService::rechargePayment($user,$money,$order);*/
       /* $order=\app\admin\model\shopro\order\Order::find(15);
        $user=User::find($order["user_id"]);
        Db::startTrans();
       try {
           // 添加消费金额
           UserService::consume($user, $order['pay_fee']);
           //新增 lina start
           //支付成功--减上级货款
           $res1=$this->reducePayment($user,$order, "order");
           // 修改用户累计消费（pv值）
           UserService::consumePv($user, $order);
           //计入奖金池
           $res=$this->bonus($user,$order);
           //统计优秀市场奖励
           $this->market($user,$order);
           // 新增业绩记录（pv值）
           //UserService::performance($user, $order['pv_price']);
           //分配订单给个体户
           $config = ShoproConfig::getConfigs('shop.bonus.bonus_individuality', false);
           if(!empty($config) && $config["status"]==1){
               $redis_key = 'individuality|store';
               if(!redis_cache()->exists($redis_key)){
                   $store=Individuality::where(["status"=>2])->select();
                   foreach ($store as $key => $store) {
                       redis_cache()->rPush($redis_key, $store['id']);
                   }
               }
               if(redis_cache()->exists($redis_key)){
                   $value = redis_cache()->blPop($redis_key, 1);
                   if ($value) {
                       $individuality_id = $value[1]; //获取到个体户id
                       // 业务代码
                       $data=["individuality_id"=>$individuality_id];
                       $config["divvy_rate"]=$config["divvy_rate"]??3;
                       $money=bcmul($order["pv_price"],($config["divvy_rate"]/100),2);//分红
                       $data["individuality_money"]=$money;//个体户分红
                       $data["individuality_rate"]=$config["divvy_rate"];//个体户分红比例
                       \app\admin\model\shopro\order\Order::where(["id"=>$order->id])->update($data);
                       // 再插入列表底部
                       redis_cache()->rPush($redis_key, $individuality_id);
                       //修改个体户可提现金额
                       WalletService::changeIndividuality($individuality_id, $money, [
                           'order_id' => $order->id,
                           'order_sn' => $order->order_sn,
                       ]);
                   }
               }
           }
           Db::commit();
       } catch (ValidateException|PDOException|Exception $e) {
           Db::rollback();
           $this->error($e->getMessage());
       }

       die();*/
       /* (new AgentService(171))->runAgentUpgradePlan();
        die();*/
        /*$order=\app\admin\model\shopro\order\Order::find(59);
        $user=User::find($order["user_id"]);
        // 修改用户累计消费（pv值）
        UserService::consumePv($user, $order);
        die();*/
        $user = auth_user();
        $id = $this->request->param('id');
        $activity_id = $this->request->param('activity_id');

        // 存一下，获取器获取指定活动的时候会用到
        session('goods-activity_id:' . $id, $activity_id);
        $service = new GoodsService(function ($goods, $service) use ($activity_id) {
            $goods->service = $goods->service;
            $goods->skus = $goods->skus;
            
            if (!$activity_id) {
                $goods->activities = $goods->activities;
                $goods->promos = $goods->promos;
            } else {
                $goods->activity = $goods->activity;
                $goods->original_goods_price = $goods->original_goods_price;
            }
            return $goods;
        });

        $goods = $service->show()->activity($activity_id)->with(['max_sku_price' => function ($query) {      // 计算价格区间用(不知道为啥 with 必须再 show 后面)
            $query->where('status', 'up');
        }, 'favorite'])->where('id', $id)->find();
        if (!$goods) {
            $this->error(__('No Results were found'));
        }

        // 添加浏览记录
        GoodsLog::addView($user, $goods);

        // 处理商品规格
        $skuPrices = $goods['new_sku_prices'];
        $content = $goods['content'];
        $goods = $goods->toArray();
        $goods['sku_prices'] = $skuPrices;
        $goods['content'] = $content;
        unset($goods['new_sku_prices']);

        $this->success('获取成功', $goods);
    }



    /**
     * 获取指定活动相关商品
     *
     * @return void
     */
    public function activity()
    {
        $activity_id = $this->request->param('activity_id');
        $need_buyers = $this->request->param('need_buyers', 0);      // 需要查询哪些人在参与活动
        $activity = Activity::where('id', $activity_id)->find();
        if (!$activity) {
            $this->error(__('No Results were found'));
        }
        $goodsIds = $activity->goods_ids ? explode(',', $activity->goods_ids) : [];

        // 存一下，获取器获取指定活动的时候会用到
        foreach ($goodsIds as $id) {
            session('goods-activity_id:' . $id, $activity_id);
        }
        $service = new GoodsService(function ($goods) use ($need_buyers) {
            if ($need_buyers) {
                $goods->buyers = $goods->buyers;    
            }
            $goods->activity = $goods->activity;
            return $goods;
        });

        $goods = $service->activity($activity_id)->whereIds($goodsIds)->show()->order('weigh', 'desc')->select();
        $goods = collection($goods)->toArray();
        foreach ($goods as &$gd) {
            unset($gd['new_sku_prices'], $gd['activity']);
        }
        $this->success('获取成功', $goods);
    }



    /**
     * 获取指定活动相关商品,带分页
     *
     * @param Request $request
     * @return void
     */
    public function activityList()
    {
        $activity_id = $this->request->param('activity_id');
        $activity = Activity::where('id', $activity_id)->find();
        if (!$activity) {
            $this->error(__('No Results were found'));
        }
        $goodsIds = $activity->goods_ids ? explode(',', $activity->goods_ids) : [];

        // 存一下，获取器获取指定活动的时候会用到
        foreach ($goodsIds as $id) {
            session('goods-activity_id:' . $id, $activity_id);
        }
        $service = new GoodsService(function ($goods) {
            $goods->promos = $goods->promos;
            return $goods;
        });
        $goods = $service->activity($activity_id)->whereIds($goodsIds)->show()->order('weigh', 'desc')->paginate();
        $this->success('获取成功', $goods);
    }

    public function pay()
    {
        (new AgentService(50073))->runAgentUpgradePlan();
        die();
      $subMerchantId="440248170080";
        $mer_prtcl_no="1111111111";
        $orderId="1111111111";
        $mer_url="https://xbnl.westts.cn/addons/shopro/pay/notify";
        $user=$this->auth->getUser();
        $user["id"]=2;
        $openid=ThirdOauth::where(["user_id"=>$user["id"]])->column("openid")[0];
        /* $pay=new \addons\shopro\icbc\ICBCPay(9);
       $res=$pay->appPay($subMerchantId, $mer_prtcl_no, $orderId . "",
           9, '', 100 . "", '', $this->request->ip(), $mer_url);
       $pay=new \addons\shopro\icbc\ICBCPay();
       $res=$pay->demo();
       dump($res);die();*/
        $pay=new \addons\shopro\icbc\ICBCPay(9);
        $res=$pay->appPay($subMerchantId, $mer_prtcl_no, $orderId, 100,$subMerchantId, '', $this->request->ip(), $mer_url);
        dump($res);die();
        $data = [
            'serviceUrl' => 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1',
            'biz_content' => get_object_vars(new ICBCPayBizContentParameter($subMerchantId, $mer_prtcl_no, $orderId . "",
                9, '', 100 . "", '', $this->request->ip(), $mer_url)),
            'extraParams' => [],
            'method' => "POST",
            'isNeedEncrypt' => true
        ];

        return $this->client->execute($data, $orderId, "");
        die();
       /* $count=0;
        $agent=\app\admin\model\shopro\commission\Agent::find(170);
        $user_ids=UserModel::where(["parent_user_id"=>170])->column("id");

        $child_agent_level_1=\app\admin\model\shopro\commission\Agent::whereIn("user_id",$user_ids)->select();
        foreach ($child_agent_level_1 as $v){
            $child_agent_level=$v["child_agent_level_1"];
            if($v["level"]>=3){
                $count++;
            }else{
                if(!empty($child_agent_level)){
                    foreach ($child_agent_level as $ks=>$vs){
                        if($ks>=3){
                            $count++;
                            continue;
                        }
                    }
                }
            }
        }
        dump($count);die();*/
        $user=$this->auth->getUser();
        $user["id"]=2;
        $openid=ThirdOauth::where(["user_id"=>$user["id"]])->column("openid")[0];
        $payOper = new PayOper();
        $payment="icbc";
        $order_type="order";
        $order=\app\admin\model\shopro\order\Order::find(12);
        /*$payModel = $payOper->{$payment}($order, $order->remain_pay_fee, $order_type);
        $order_data = [
            'order_id' => $order->id,
            'out_trade_no' => $payModel->pay_sn,
            'total_amount' => $payModel->pay_fee,      // 剩余支付金额
        ];*/
        $order=[
            "order_sn"=>"202305424763535360015200",
        ];
        $mer_url="https://xbnl.westts.cn/addons/shopro/pay/notify";
        $url="https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1";
        $orig_date=date("Y-m-d",time());
        $orig_time=date("H:i:s",time());
        $orig_date_time=$orig_date."T".$orig_time;
        $biz_content=[
            "mer_id"=>"440248170080",
            "out_trade_no"=>$order["order_sn"],
            "pay_mode"=>'9',
            "access_type"=>'9',
            "mer_prtcl_no"=>'440248170080',
            "orig_date_time"=>$orig_date_time,
            "decive_info"=>"440248170080",
            "body"=>"成都本草之源生物科技有限公司"."商品",
            "fee_type"=>'001',
            "spbill_create_ip"=>request()->ip(),
            "total_fee"=>'100',
            "mer_url"=>$mer_url,
            "shop_appid"=>'wxd4887d676c7ee0d6',
            "icbc_appid"=>'11000000000000016036',
            "open_id"=>$openid,
            "expire_time"=>'1800',
            "notify_type"=>"HS",
            //非必填参数
            "union_id"=>"",
            "mer_acct"=>"",
            "attach"=>"",
            "result_type"=>"",
            "pay_limit"=>"",
            "order_apd_inf"=>"",
            "detail"=>"",
            "return_url"=>"",
            "quit_url"=>"",
        ];
        /*$biz_content=[
            "mer_id"=>"440282410020",
            "out_trade_no"=>$order["order_sn"],
            "pay_mode"=>'9',
            "access_type"=>'9',
            "mer_prtcl_no"=>'440282410020',
            "orig_date_time"=>$orig_date_time,
            "decive_info"=>"440248170080",
            "body"=>"成都本草之源生物科技有限公司"."商品",
            "fee_type"=>'001',
            "spbill_create_ip"=>request()->ip(),
            "total_fee"=>'100',
            "mer_url"=>$mer_url,
            "shop_appid"=>"wx5f033d3ed547eb99",
            "icbc_appid"=>"10000000000003248517",
            "open_id"=>"wx5f033d3ed547eb99",
            "expire_time"=>$close_minue."",
            "notify_type"=>"HS",
        ];*/
        /*$biz_content="{\"mer_id\":\"440282410020\",\"out_trade_no\":\"1918504332623056896\",\"pay_mode\":\"9\",\"access_type\":\"7\",\"mer_prtcl_no\":\"440282410020\",\"orig_date_time\":\"2022-11-09T15:59:20\",\"decive_info\":\"1908258803072532480\",\"body\":\"测试税率-课程\",\"fee_type\":\"001\",\"spbill_create_ip\":\"117.136.63.148\",\"total_fee\":\"300\",\"mer_url\":\"http://apitest.hitcxedu.com/traffic-school/icbc/payNotice\",\"shop_appid\":\"wx5f033d3ed547eb99\",\"icbc_appid\":\"10000000000003248517\",\"open_id\":\"oszoev9D7yqyF8a_q2qjmf-O4i2I\",\"union_id\":null,\"mer_acct\":null,\"expire_time\":\"1800\",\"attach\":\"courseFee\",\"notify_type\":\"HS\",\"result_type\":\"1\",\"pay_limit\":\"\",\"order_apd_inf\":null,\"detail\":null,\"return_url\":null,\"quit_url\":null,\"cust_name\":null,\"cust_cert_type\":null,\"cust_cert_no\":null}";
        $biz_content=json_decode($biz_content,true);*/
        $data=[
            "app_id"=>"11000000000000016036",
            "msg_id"=>$order["order_sn"],
            "sign"=>"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCssav8hbwKkjVxj3nojQ6HHe7+cCvWPNvbQFDzYJtIRetqxW3AzSB1Gfe7J8MgzMy4BnIWJRiIzEqapxxeFo2oJ7clILY1gkmyyYfFFQLNX0Fooy8sv+EJ2GxHZr4io5Idy0ALN1ctPXFVZaI1OSxn8N06MixQJImzo3ObHVkCHOtzifUAeH+rDYh5XKACQ1dcACi2YPibZdm3rK67Xuguzmbf2NnEJIjMhI/vbq50n0eR+601r9t64BuKqBgu5UXKyzPHgcN3OEbJZQ0ScvKYfguAHNy/E3UM0r8TkceF9WtzuGzGSmOO3BLnT01xz/VajkX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S+Zn4p0MDIKzoIHNE5JkNXJFwxp4o0cbnfyEEZqdVruX80D8hyKgPDnYuCeDLBqnKBkrdfq8jNTFDEBmFk+V4+HRj/7aL2WXKOkW3O1AOz+yjTHhSFwc4He1jKCAz585aKWQG1TWPHlnp2QzGlqpsD/W3tIjO9etYIc=",
            "timestamp"=>$orig_date." ".$orig_time,
            "biz_content"=>$biz_content,
            "sign_type"=>"RSA2",
            //非必填参数
            /*"format"=>"json",
            "charset"=>"UTF-8",
            "encrypt_type"=>"AES",
            "ca"=>"",*/
        ];
        $data=json_encode($data);
        dump($data);
        $result = Http::post($url,$data );
        dump($result);die();

        die();
        $request = array(
            "serviceUrl" => 'http://ip:port/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1',
            "method" => 'POST',
            "isNeedEncrypt" => false,
            "biz_content" => array(
                "mer_id"=>"020053010625",
                "mer_prtcl_no"=>"0200530106250201",
                "pay_mode"=>"10",
                "access_type"=>"5",
                "out_trade_no"=>"AAPPT20051202205754714",
                "decive_info"=>"9774d56d682e549c",
                "body"=>"勇士总冠军",
                "fee_type"=>"001",
                "icbc_appid"=>"10000000000004095503",
                "mer_acct"=>"1402027109600325515",
                "mer_url"=>"http://5.1fendb.com/recall/recall.php",
                "orig_date_time"=>"2020-05-12T02:20:51",
                "spbill_create_ip"=>"27.155.168.208",
                "total_fee"=>"1",
                "notify_type"=>"HS"
            )

        );
//以下构造函数第1个参数为appid，第2个参数为RSA密钥对中私钥，第6个参数为API平台网关公钥
        $client = new DefaultIcbcClient('10000000000004095503',
            ' MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYLo0htdHwedbvoJA0o5AA/UUE1zb/J4OO9SYmeMBZnLeiNC7TwG53PXgwCSHsp2gM02QatfohUUDHQJg/ezYCSDSMoWfYKv/dfz0DlXp1C8xOnc/im2y0PnZV1YVaTsFHnax91N7nxtfsGVRlT8e2UdkWlW0HX2QOxCBpuevDssfosA151f4JV07VHl+pyHxTS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kov7hFIEjHIqYHkGxXeJGNRoNzfxoR+ywg8GKK8Fq3dmigkB4hL+YjyBnxX0SouyLoWUZ0Jvsurr9bZ5h/qvPyLhtCQyc7QXM4fBKlOy0rxgOBIxRWKMVvJeFHEqw6SBAoGAPuR/+v2VCePORhobY0EIIRLK1sO+Q2IVJIU4ecm0irD99/uwEc+RgJF0IakYlrw1PtmhDYniXO07GMIecj4zsnnPZtkttoNxmikMrK51YsFcsz8I55XzRPPGj1V8CxpfRxmEj9ofyHYHDDvSoHAR28xJdubbn3PuB7nBp94yNWk=',
            IcbcConstants::$SIGN_TYPE_RSA,
            '',
            '',
            'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwFgHD4kzEVPdOj03ctKM7KV+16bWZ5BMNgvEeuEQwfQYkRVwI9HFOGkwNTMn5hiJXHnlXYCX+zp5r6R52MY0O7BsTCLT7aHaxsANsvI9ABGx3OaTVlPB59M6GPbJh0uXvio0m1r/lTW3Z60RU6Q3oid/rNhP3CiNgg0W6O3AGqwIDAQAB',
            '',
            '',
            '',
            '');
        $resp = $client->execute($request,'123131123asda','');//执行调用;msgId消息通讯唯一编号，要求每次调用独立生成，APP级唯一
        echo $resp;
        $respObj = json_decode($resp,true);
        if($respObj["return_code"] == 0){ //sucess
            echo $respObj["return_msg"];
        }else{//fail
            echo $respObj["return_msg"];
        }
        dump($result);die();
    }
}
